'use strict';

// 上课考勤管理

const classAttendanceModel = require('../models/class_attendance.model');
const classroomModel = require('../models/classroom.model');
const StudentRecordsModel = require('../models/record_student.model');
const Code = require('../common/error_code');
const Util = require('../utils/hobot_util');
const XLSX = require('xlsx');
const nodeXlsx = require('node-xlsx');
const moment = require('moment');


// 编辑上课信息
async function update_class_attendance(ctx){
    const params = ctx.request.body;
    // 校验参数
    if (!params._id || !params.class_teacher || !params.class_start_time || !params.class_end_time) {
        return ctx.error(Code.RET_ERR_PARAM);
    }
    const timeRegex = /^((0|1)\d|2[0-3])([0-5]\d)$/;
    if(timeRegex.test(params.class_start_time)&&timeRegex.test(params.class_end_time)&& params.class_end_time>params.class_start_time){
       const data =  await classAttendanceModel.findOneAndUpdate({_id:params._id},{
           class_teacher:params.class_teacher,
           class_start_time:params.class_start_time,
           class_end_time:params.class_end_time
       })
       // 更新打卡信息 
       if(data){
           const student_collection = data.student_collection
           const device_collection = data.device_collection
           const startTime = new Date(data.attendance_start_date).setHours(params.class_start_time.slice(0,2),params.class_start_time.slice(2),0,0) - 1000*60*30
           const endTime = new Date(data.attendance_start_date).setHours(params.class_end_time.slice(0,2),params.class_end_time.slice(2),0,0) + 1000*60*30
           if(student_collection&&student_collection.length&&device_collection&&device_collection.length){
             const deviceIds = device_collection.map(item=>item.device_id)
             for(let student of student_collection){
                 if(student.student_num){
                    const studentRecords = await StudentRecordsModel.find({
                        // s_id:student.student_id,
                        s_num:student.student_num,
                        d_id:{
                            $in:deviceIds
                        },
                        c_time:{
                            $gte:startTime/1000,
                            $lte:endTime/1000
                        }
                    },{c_photo:0})
                    if(studentRecords&&studentRecords.length){
                        student.attendance_start_time = studentRecords[0].c_time*1000
                        student.attendance_end_time = studentRecords[studentRecords.length-1].c_time*1000
                    }else{
                        student.attendance_start_time = student.attendance_end_time = ''
                    }
                 }
             }
             await classAttendanceModel.updateOne({_id:data._id},{
                 $set:{
                    student_collection
                }
            },{upsert:true})
           }
           return ctx.success(Code.REQUEST_SUCCESS('更新成功'))
       }
       return ctx.error(Code.REQUEST_ERROR('该课程不存在'))
    }else{
        return ctx.error(Code.REQUEST_ERROR('日期格式错误'));
    }
}

// 课表考勤表
async function query(ctx) {
    const params = ctx.request.body;
    // 校验参数
    if (!params.page_num || !params.page_size) {
        return ctx.error(Code.RET_ERR_PARAM);
    }
    let cdt = {
    };
    if (params.group_name) {
        cdt.group_name = { $regex: params.group_name };
    }
    if (params.campus_name) {
        cdt.campus_name = { $regex: params.campus_name };
    }
    if (params.campus_id) {
        cdt.campus_id = params.campus_id;
    }
    if (params.class_name) {
        cdt.class_name = { $regex: params.class_name };
    }
    if (params.class_id) {
        cdt.class_id = params.class_id;
    }
    if (params.classroom_name) {
        cdt.classroom_name = { $regex: params.classroom_name };
    }
    if (params.classroom_id) {
        cdt.classroom_id = params.classroom_id;
    }
    if (params.class_date_from&&params.class_date_to) {
        cdt.attendance_start_date = {
            $lte:params.class_date_to,
            $gte:params.class_date_from
        };
    }
    if (params.class_type) {
        cdt.class_type = { $regex: params.class_type };
    }
    if(params.class_start_time&&params.class_end_time){
        cdt.class_start_time = {
            $gte: params.class_start_time
        }
        cdt.class_start_time = {
            $lte: params.class_end_time
        }
    }
    const attendances = await Util.pageQuery(params.page_num, params.page_size, classAttendanceModel,
        cdt, '', '',{_id:-1});
    ctx.success(Code.REQUEST_SUCCESS('查询成功'), {
        page_num: params.page_num,
        page_size: params.page_size,
        total: attendances.total,
        result: attendances.results
    });
}

// 课表考勤表统计
async function stat(ctx) {
    const params = ctx.request.body;
    const currentTimeStamp = new Date().setHours(0,0,0,0);
    const dateTimeReg = /^\d{4}\/(0?\d|1[12])\/(0?\d|[12]\d|3[01])\s+((0?|1)\d|2[0-3]):(0?|[1-5])\d(:(0?|[1-5])\d)?$/
    // 校验参数
    
    let date_from,date_to;
    if (!params.class_date_from || !params.class_date_to) {
        date_from = currentTimeStamp;
        date_to = currentTimeStamp + 1000*60*60*24;
    }else if(!dateTimeReg.test(params.class_date_from)||!dateTimeReg.test(params.class_date_to)){
        return ctx.error(Code.REQUEST_ERROR('日期格式错误'))
    }else{
        date_from = + new Date(params.class_date_from)
        date_to = + new Date(params.class_date_to)
    }
    let cdt = {
        attendance_start_date: {
            $lte:date_to,
            $gte:date_from
        }
    };
    if (params.group_name) {
        cdt.group_name = { $regex: params.group_name };
    }
    if (params.campus_name) {
        cdt.campus_name = { $regex: params.campus_name };
    }
    if (params.class_name) {
        cdt.class_name = { $regex: params.class_name };
    }
    if (params.classroom_name) {
        cdt.classroom_name = { $regex: params.classroom_name };
    }
    if (params.class_type) {
        cdt.class_type = { $regex: params.class_type };
    }
    const attendances = await Util.pageQuery(params.page_num, params.page_size, classAttendanceModel,
        cdt, '', '',{_id:-1});
    // attendances.results.forEach(item=>{
    //     if(item.class_start_time&&item.class_end_time){
    //         const array1 = item.class_start_time.split('')
    //         item.class_start_time = array1.slice(0,2).concat(':',array1.slice(2)).join('')
    //         const array2 = item.class_end_time.split('')
    //         item.class_end_time = array2.slice(0,2).concat(':',array2.slice(2)).join('')
    //     }
    // })
    ctx.success(Code.REQUEST_SUCCESS('查询成功'), 
    attendances.results
    // {
    //     page_num: params.page_num,
    //     page_size: params.page_size,
    //     total: attendances.total,
    //     result: attendances.results
    // }
    );
}

// 导出考勤
async function export_class_attendance(ctx){
    const params = ctx.request.body
    // 校验参数
    if (!params.ids && !Array.isArray(params.ids)) {
        return ctx.error(Code.RET_ERR_PARAM);
    }
    try{
        const ids = params.ids
        let count = 0,SheetNames=[],Sheets={},currentTime = +new Date()
        const allData = []
        const _headers = [
            { key: 'campus_name', title: '上课校区' },
            { key: 'classroom_name', title: '教室名称' },
            { key: 'class_name', title: '班级名称' },
            { key: 'attentdance_date', title: '上课日期' },
            { key: 'attentdance_time', title: '上课时间' },
            { key: 'class_type', title: '项目' },
            { key: 'class_teacher', title: '主讲老师' },
            { key: 'student_name', title: '学生姓名' },
            { key: 'student_num', title: '学号' },
            { key: 'attendance_start_time', title: '最早打卡时间' },
            { key: 'attendance_end_time', title: '最晚打卡时间' },
            { key: 'remark', title: '标示' },
        ];  
        const dayObj = {
            0:'周天',
            1:'周一',
            2:'周二',
            3:'周三',
            4:'周四',
            5:'周五',
            6:'周六',
        }
        const options = {'!cols': new Array(_headers.length).fill({ wch: 16, horizontal: "center" })};
        const itemHeaders = _headers.map(({title})=>title)
        for(let id of ids){
            const itemData = [itemHeaders]
            const data = await classAttendanceModel.findById(id)
            if(data){
                count++
                SheetNames.push(`sheet${count}`)
                const temp = _headers.slice(0,-5).map(({key})=> {
                    if(key==='attentdance_date'){
                        const date = new Date(data.attendance_start_date)
                        return moment(data.attendance_start_date).format('YYYY-MM-DD') + '(' + dayObj[date.getDay()] + ')'
                    }else if(key==='attentdance_time'){
                        return data.class_start_time.slice(0,2)+':'+data.class_start_time.slice(2)+'~'+data.class_end_time.slice(0,2)+':'+data.class_end_time.slice(2)
                    }
                    return data[key]
                })
                const student_collection = (data.student_collection||[]).filter(item=>!item.is_invalid||item.is_invalid>=10)
                student_collection.forEach((item,i)=>{
                    const childTemp = []
                    _headers.slice(-5).forEach(({key})=>{
                        if(key==='attendance_start_time'){
                            const startTime = item[key]?moment(item[key]).format('HH:mm'):'-'
                            return childTemp.push(startTime)
                        }else if(key==='attendance_end_time'){
                            const endTime = item[key]?moment(item[key]).format('HH:mm'):'-'
                            return childTemp.push(endTime)
                        }else if(key==='remark'){
                            let rk = '';
                            let classStartTime = data.class_start_time;
                            let classEndTime = data.class_end_time;
                            if(item.is_invalid&&item.is_invalid>=10){
                                rk = '蹭课'
                            }else if(currentTime<classEndTime){
                                rk = '-'
                            }else if(!item.attendance_start_time){
                                rk = '旷课'
                            } else if(classStartTime<item.attendance_start_time){
                                rk = '迟到'
                            } else if(classEndTime>item.attendance_end_time){
                                rk = '早退'
                            } else {
                                rk = '正常'
                            }
                            return childTemp.push(rk)
                        }
                        childTemp.push(item[key]||'')
                    })
                    itemData.push(temp.concat(childTemp))
                })
                allData.push(itemData)
            }
        }
        const xslsData = allData.map((data,i)=>Object.assign({},{name:`sheet${i+1}`,data,options}))
        const bufferData = nodeXlsx.build(xslsData)
        return ctx.body = bufferData
    }catch(err){
        console.log(err)
        return ctx.error(Code.REQUEST_ERROR('导出失败'))
    } 
}

// 查看某天班级考勤
async function query_daily_attendance(ctx){
    const params = ctx.request.body
    const dateReg = /^\d{4}\/(0?\d|1[12])\/(0?\d|[12]\d|3[01])$/
    // 校验参数
    if (!params.class_num) {
        return ctx.error(Code.REQUEST_ERROR('缺少查询参数:class_num班级编号'));
    }
    if (!params.class_date) {
        return ctx.error(Code.REQUEST_ERROR('缺少查询参数:class_date考勤日期'));
    }
    if(!dateReg.test(params.class_date)){
        return ctx.error(Code.REQUEST_ERROR('日期参数格式错误'));
    }
    const classDate = +moment(params.class_date,'YYYY/MM/DD')
    try{
        const allData = []
        const _headers = [
            { key: 'campus_name', title: '上课校区' },
            { key: 'classroom_name', title: '教室名称' },
            { key: 'class_name', title: '班级名称' },
            { key: 'attentdance_date', title: '上课日期' },
            { key: 'attentdance_time', title: '上课时间' },
            { key: 'class_type', title: '项目' },
            { key: 'class_teacher', title: '主讲老师' },
            { key: 'student_name', title: '学生姓名' },
            { key: 'student_num', title: '学号' },
            { key: 'attendance_start_time', title: '最早打卡时间' },
            { key: 'attendance_end_time', title: '最晚打卡时间' },
            { key: 'remark', title: '标示' },
        ];  
        const dayObj = {
            0:'周天',
            1:'周一',
            2:'周二',
            3:'周三',
            4:'周四',
            5:'周五',
            6:'周六',
        }
        const data = await classAttendanceModel.findOne({
            class_num:params.class_num,
            attendance_start_date:classDate
        })
        if(data){
            let temp = {},currentTime = +new Date();
            _headers.slice(0,-5).forEach(({key,title})=> {
                if(key==='attentdance_date'){
                    const date = new Date(data.attendance_start_date)
                    return temp[title] = moment(data.attendance_start_date).format('YYYY-MM-DD') + '(' + dayObj[date.getDay()] + ')'
                }else if(key==='attentdance_time'){
                    return temp[title] = moment(data.class_start_time).format('HH:ss')+'~'+moment(data.class_end_time).format('HH:ss')
                }
                temp[title] = data[key]
            })
            const student_collection = (data.student_collection||[]).filter(item=>!item.is_invalid||item.is_invalid>=10)
            student_collection.forEach((item,i)=>{
                const childTemp = Object.assign({},temp);
                _headers.slice(-5).forEach(({key,title})=>{
                    if(key==='attendance_start_time'){
                        const startTime = item[key]?moment(item[key]).format('HH:mm:ss'):'-'
                        return childTemp[title] = startTime
                    }else if(key==='attendance_end_time'){
                        const endTime = item[key]?moment(item[key]).format('HH:mm:ss'):'-'
                        return childTemp[title] = endTime
                    }else if(key==='remark'){
                        let rk = '-';
                        let classStartTime = moment(data.class_start_time).format('HH:ss')
                        let classEndTime = moment(data.class_end_time).format('HH:ss')
                        // let classStartTime = new Date(data.attendance_start_date).setHours(data.class_start_time.slice(0,2),data.class_start_time.slice(-2),0,0);
                        // let classEndTime = new Date(data.attendance_start_date).setHours(data.class_end_time.slice(0,2),data.class_end_time.slice(-2),0,0);
                        if(item.is_invalid&&item.is_invalid>=10){
                            rk = '蹭课'
                        }else if(currentTime<classEndTime){
                            rk = '-'
                        }else if(!item.attendance_start_time){
                            rk = '旷课'
                        } else if(classStartTime<item.attendance_start_time){
                            rk = '迟到'
                        } else if(classEndTime>item.attendance_end_time){
                            rk = '早退'
                        } else {
                            rk = '正常'
                        }
                        return childTemp[title] = rk
                    }else{
                        return childTemp[title] = item[key]||''
                    }
                })
                allData.push(childTemp)
            })
        }
        return ctx.success(Code.REQUEST_SUCCESS('查询成功'),allData)
    }catch(err){
        console.log(err)
        return ctx.error(Code.REQUEST_ERROR('查询失败'))
    } 
}

exports.update_class_attendance = update_class_attendance;

exports.export_class_attendance = export_class_attendance;

exports.query_daily_attendance = query_daily_attendance;

exports.query = query;

exports.stat = stat;